#include <stdio.h>
#include <string.h> //strlen
#include <unistd.h> //sleep
#include <errno.h>
#include <mosquitto.h>

char* uid = "4e78c607dbbc9f4d6b5c16ffa5622fb7";

//写文件
//参数1：文件路径
//参数2：写入的字符串
//返回值：成功返回0，失败返回错误码
int write_file(char* path, char* data)
{
    FILE* fp = fopen(path, "w");
    if (fp == NULL)
    {
        perror("fopen");
        return errno;
    }

    fprintf(fp, data);

    fclose(fp);
    return 0;
}

void on_message(struct mosquitto * client, void * data, const struct mosquitto_message * msg)
{
    printf("从%s主题收到消息: %*s\n", msg->topic, msg->payloadlen, msg->payload);
    if (strncmp(msg->topic, "test002", strlen("test002")) == 0)
    {
        //处理开关灯命令
        if (strncmp(msg->payload, "on", 2) == 0)
        {
            //开灯
            write_file("/sys/class/leds/led1/brightness", "1");
            printf("开灯\n");
        }

        if (strncmp(msg->payload, "off", 3) == 0)
        {
            //关灯
            write_file("/sys/class/leds/led1/brightness", "0");
            printf("关灯\n");
        }
    }
}

int main()
{
    //初始化mosquitto函数库
    mosquitto_lib_init();
    //创建MQTT客户端
    struct mosquitto* client = mosquitto_new(uid, true, NULL);
    if (client == NULL)
    {
        perror("mosquitto_new");
        mosquitto_lib_cleanup();
        return 1;
    }

    //连接MQTT服务器
    int error = mosquitto_connect(client, "bemfa.com", 9501, 60);
    if (error != MOSQ_ERR_SUCCESS)
    {
        printf("MQTT服务器连接失败: %s\n", mosquitto_strerror(error));
        mosquitto_destroy(client);
        mosquitto_lib_cleanup();
        return 1;
    }

    printf("MQTT服务器连接成功\n");

    mosquitto_message_callback_set(client, on_message);

    //订阅主题
    error = mosquitto_subscribe(client, NULL, "test002", 0);
    if (error != MOSQ_ERR_SUCCESS)
    {
        printf("主题订阅失败: %s\n", mosquitto_strerror(error));
    }

    printf("主题订阅成功\n");

    //启动任务接收消息
    mosquitto_loop_start(client);

    //主循环，读取传感器信息，上报到云平台
    for (int i = 0; ;i++)
    {
        char msg[10];
        sprintf(msg, "hello %d", i);
        //发送消息
        mosquitto_publish(client, NULL, "test", strlen(msg), msg, 0, false);
        printf("消息发送成功: %s\n", msg);
        sleep(10);
    }

    //销毁客户端，释放资源
    mosquitto_destroy(client);

    //清理函数库占用的资源
    mosquitto_lib_cleanup();
    return 0;
}